

#import "FZ_BoFang_Two_ViewController.h"
#import "FZ_BoFang_Two_TableViewCell_One.h"
#import "FZ_BoFang_Two_TableViewCell_Two.h"
#import "FZ_BoFang_TwoCell_XiangQing_ViewController.h"
#import "FZ_BoFang_One_ViewController.h"
#import <UIImageView+WebCache.h>
#import "BaseHeader.h"
#import "CustomerNetworking.h"
#import "CoreDataManager.h"
#import "CXMusicModel.h"
#import "CXSelectSaveViewController.h"
#import "FZ_RightCreatViewDongH.h"
#import "FZ_BoFangTouXiangCreatViewDongH.h"
#import <UMSocial.h>
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define WIDTH_PRO(X) (X)*(SCREEN_WIDTH/375)

#define HEIGHT_PRO(Y) (Y)*(SCREEN_HEIGHT/667)

//#import "POP.h"
//#import "POPSpringAnimation.h"
//#import "POPSpringAnimationInternal.h"
//#import "POPSpringSolver.h"

static  BOOL TouXiangStateFF = YES;
@interface FZ_BoFang_Two_ViewController ()<UITableViewDataSource,UITableViewDelegate,ImageViewTapDelegate,BoFangXingQingDelegate, STKAudioPlayerDelegate,DongHuaDelegate,FZ_BoFangXingQingDelegate,FZ_FenXiangXingQingDelegate>
@property (nonatomic , retain) UIView *backGroundView;
@property (nonatomic , retain) UIImageView *backGroundImageView;
@property (nonatomic ,retain) UITableView *tableViewOne;
@property (nonatomic ,retain)NSTimer *timer;
@property (nonatomic, retain) CoreDataManager *manager;
@property (nonatomic, retain)FZ_BoFang_Two_TableViewCell_One *cellF;
@property (nonatomic, retain)NSArray *tempArray;
@property (nonatomic, retain) UIView *viewDown;
@property (nonatomic, retain) UISlider *sliderVolumeProgress;
@property (nonatomic ,copy) NSString *YinYueState;
@property (nonatomic, assign)BOOL TouXiangStateF;
@property (nonatomic ,retain) FZ_BoFangTouXiangCreatViewDongH *CreatViewS;
@property (nonatomic ,retain) UITapGestureRecognizer *tapTouXiangS;
@property (nonatomic, assign)BOOL playBOOL;//判断播放按钮

@property (nonatomic, retain)UIView *shareView;

//第二种cell
@property (nonatomic, retain)FZ_BoFang_Two_TableViewCell_Two *cellTwo;

@end
@implementation FZ_BoFang_Two_ViewController

- (void)dealloc {
    [_backGroundImageView release];
    [_backGroundView release];
    [_tableViewOne release];
    [_cellT release];
    [_cellF release];
    [_timer release];
    [_player release];
    [_allMusicArray release];
    [_manager release];
    [_detailModel release];
    [_tempArray release];
    [_shareView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //分享
    self.shareView = [[UIView alloc] initWithFrame:CGRectMake(100, HEIGHT_PRO(667), 100, 200)];
    self.shareView.backgroundColor = [UIColor redColor];

    self.tempArray = [NSArray array];
    self.tabBarController.tabBar.hidden = YES;
    self.player = [[STKAudioPlayer alloc]initWithOptions:(STKAudioPlayerOptions){
        .flushQueueOnSeek = YES,
        .enableVolumeMixer = YES
    }];
    self.player.delegate = self;
    [self createImageView];
    [self createTableView];
    [self creatViewDown];
    [self CreatTransLayer];
    //刚进这个页面，让他处于播放的状态
    if (self.player.state == STKAudioPlayerStatePaused) {
        self.player.state = STKAudioPlayerStatePlaying;
    }if (self.player.state == STKAudioPlayerStatePlaying) {
        [self givePicToplayButtonWhenPlay];
        [self loadPlayData];
        self.player.state = STKAudioPlayerStatePlaying;
    }else{
        [self givePicToplayButtonWhenPlay];
        [self loadPlayData];
        self.player.state = STKAudioPlayerStatePlaying;
    }
    self.manager = [CoreDataManager shareManager];
}
- (void)receiveNotificationTouXiangK:(NSNotification *)notification{
    self.TouXiangStateF = YES;
}
- (void)receiveNotificationTouXiangT:(NSNotification *)notification{
    self.TouXiangStateF = NO;
}
-(void)CreatTransLayer{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationTouXiangK:) name:YINYUE_STATE_K object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationTouXiangT:) name:YINYUE_STATE_T object:nil];
}
- (void)creatViewDown{
    self.viewDown = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight + 35.f , ScreenWidth, 35.f)];
    self.viewDown.userInteractionEnabled = YES;
    self.viewDown.alpha = 0.6f;
    [self.cellT.contentView bringSubviewToFront:self.viewDown];
    [self.tableViewOne addSubview:self.viewDown];
    [_viewDown release];
    
#pragma mark 创建声音的进度条
    self.sliderVolumeProgress = [[UISlider alloc] initWithFrame:CGRectMake(100.f, - 4.f, 175.f, 15.f)];
    [self.sliderVolumeProgress setThumbImage:[UIImage imageNamed:@"labaBaiSe16.png"] forState:UIControlStateNormal];
    self.sliderVolumeProgress.value = 0.5;
    [self.sliderVolumeProgress addTarget:self action:@selector(volumeAction:) forControlEvents:UIControlEventValueChanged];
    [self.viewDown addSubview:self.sliderVolumeProgress];
    [_sliderVolumeProgress release];
}
#pragma mark 解析播放数据
-(void)loadPlayData{
    [self.player play:self.playUrl];
    [self secondGiveData];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
}
#pragma mark 播放单例
+(FZ_BoFang_Two_ViewController *)sharePlayer{
    static FZ_BoFang_Two_ViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[FZ_BoFang_Two_ViewController alloc] init];
    });
    return  player;
}
#pragma mark - 外部调用方法
- (void)setData:(NSMutableArray *)songs row:(NSInteger)row
{
  //如果当前播放的音乐就是传入的音乐，那么就直接返回
    //判断暂停进来的时候是否是同一首歌
    if (self.playUrl == [[songs objectAtIndex:row] source]){
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self.player play:[[songs objectAtIndex:row] source]];
        }
      return;
    }
    //如果不是同一首歌
    else{
        [self givePicToplayButtonWhenPlay];
    }
    self.player.delegate = self;
    self.allMusicArray = [[NSMutableArray alloc]init];
    self.allMusicArray = songs;
    self.indexRow = row;
    [self loadPlayData];
}
- (void)createImageView{
#pragma  这么写为什么距离就小
    self.backGroundView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.backGroundImageView = [[UIImageView alloc] initWithFrame:self.backGroundView.frame];
    [self.backGroundImageView sd_setImageWithURL:[NSURL URLWithString:self.pic] placeholderImage:WAIT_PICTURE];
    UIVisualEffectView *sual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle: UIBlurEffectStyleDark]];
    sual.frame = CGRectMake(0, 0, self.backGroundView.frame.size.width, self.backGroundView.frame.size.height);
    [self.backGroundImageView addSubview:sual];
    sual.alpha = 0.7;
    [sual release];
    [self.backGroundView addSubview:self.backGroundImageView];
    [self.view addSubview:self.backGroundView];
}
- (void)createTableView{
    self.tableViewOne = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    self.tableViewOne.delegate = self;
    self.tableViewOne.dataSource = self;
    self.tableViewOne.bounces = NO;
    self.tableViewOne.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableViewOne];
    [_tableViewOne release];
    [self.tableViewOne registerClass:[FZ_BoFang_Two_TableViewCell_One class] forCellReuseIdentifier:@"FZ_BoFang_Two_TableViewCell_One"];
    [self.tableViewOne registerClass:[FZ_BoFang_Two_TableViewCell_Two class] forCellReuseIdentifier:@"FZ_BoFang_Two_TableViewCell_Two"];
    [self.tableViewOne registerClass:[FZ_BoFang_Two_TableViewCell_Three class] forCellReuseIdentifier:@"FZ_BoFang_Two_TableViewCell_Three"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        self.cellF = [tableView dequeueReusableCellWithIdentifier:@"FZ_BoFang_Two_TableViewCell_One"];
        self.cellF.delegateBack = self;
        self.cellF.delegateDongHua = self;
        //收藏按钮
        [self.cellF.saveButton addTarget:self action:@selector(saveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.cellF.saveButton setBackgroundImage:[UIImage imageNamed:@"likeWhite.png"] forState:UIControlStateNormal];
        [self.cellF.saveButton setBackgroundImage:[UIImage imageNamed:@"icon_star_collection.png"] forState:UIControlStateSelected];
        [self.cellF.saveButton setTag:self.indexRow];
        [self.cellF.saveButton setSelected:NO];
        [self search];
        for (CXMusicModel *temopModel in self.tempArray) {
            if ([temopModel.source isEqualToString:self.playUrl]) {
                [self.cellF.saveButton setSelected:YES];
            }
        }
#pragma mark 点光盘进来判断暂停按钮的状态
        if (self.cellF.labelPlayTitle.text == NULL) {
            [self givePicToplayButtonWhenPause];
        }
#pragma mark 给歌曲名和旋转的图片
        [self secondGiveData];
        self.cellF.backgroundColor = [UIColor clearColor];
        self.cellF.selectionStyle = UITableViewCellSelectionStyleNone;
        self.cellF.viewTouXiang = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 80, 80)];
        self.cellF.viewTouXiang.backgroundColor = [UIColor clearColor];
        [self.cellF.contentView addSubview:self.cellF.viewTouXiang];
        self.cellF.viewTouXiang.userInteractionEnabled = YES;
        self.cellF.viewTouXiang.layer.shadowOpacity = 1;
        self.cellF.viewTouXiang.layer.shadowColor = [UIColor yellowColor].CGColor;
        self.cellF.viewTouXiang.layer.shadowRadius = 10;
        self.cellF.viewTouXiang.layer.cornerRadius = 40;
        self.cellF.viewTouXiang.layer.borderColor = [UIColor clearColor].CGColor;
        self.cellF.viewTouXiang.layer.borderWidth = 2;
        UIImage *imageRight = RIGHT_ITEM_BAR;
        imageRight = [imageRight imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.cellF.imageViewTouXiang removeFromSuperview];
        self.cellF.imageViewTouXiang = [[UIImageView alloc] initWithFrame:self.cellF.viewTouXiang.frame];
        self.cellF.imageViewTouXiang.image = imageRight;
        self.cellF.imageViewTouXiang.layer.cornerRadius = 40;
        self.cellF.imageViewTouXiang.clipsToBounds = YES;
        self.cellF.imageViewTouXiang.layer.masksToBounds = YES;
        self.cellF.imageViewTouXiang.layer.backgroundColor = [UIColor blackColor].CGColor;
        self.cellF.imageViewTouXiang.layer.borderWidth = 2;
        //这里是改过的头像赋值
        [self.cellF.imageViewTouXiang sd_setImageWithURL:[NSURL URLWithString:[[self.allMusicArray objectAtIndex:self.indexRow] pic]] placeholderImage:WAIT_PICTURE];
        self.cellF.imageViewTouXiang.layer.borderColor = [UIColor whiteColor].CGColor;
        self.cellF.imageViewTouXiang.userInteractionEnabled = YES;
        [self.cellF.viewTouXiang addSubview:self.cellF.imageViewTouXiang];
        [self.cellF.imageViewTouXiang release];
        CABasicAnimation *basicanimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        [basicanimation setDuration:3];
        [basicanimation setRepeatCount:NSIntegerMax];
        [basicanimation setFromValue:[NSNumber numberWithInt:0]];
        [basicanimation setToValue:[NSNumber numberWithFloat:M_PI * 2]];
        [self.cellF.imageViewTouXiang.layer addAnimation:basicanimation forKey:@"transform"];
        basicanimation.autoreverses = YES;
        return self.cellF;
    }
    if (indexPath.row == 1) {
        self.cellTwo = [tableView dequeueReusableCellWithIdentifier:@"FZ_BoFang_Two_TableViewCell_Two"];
        self.cellTwo.delegate = self;
        self.cellTwo.fzDelegate = self;
        self.cellTwo.fzFenXiangDelegate = self;
        self.cellTwo.JieShouModelS = self.JieShouModel;
        self.cellTwo.backgroundColor = [UIColor clearColor];
        self.cellTwo.selectionStyle = UITableViewCellSelectionStyleNone;
        return self.cellTwo;
    }
    else
    {
        self.cellT = [tableView dequeueReusableCellWithIdentifier:@"FZ_BoFang_Two_TableViewCell_Three"];
        self.cellT.JieShouModelT = self.JieShouModel;
        if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
            if (self.player.state == STKAudioPlayerStatePaused) {
                [self givePicToplayButtonWhenPause];
            }
            if(self.player.state == STKAudioPlayerStatePlaying)
            {
                [self givePicToplayButtonWhenPlay];
            }
            else{
                if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
                [self givePicToplayButtonWhenPlay];
                }else{
                    [self givePicToplayButtonWhenPause];

                }
            }

        }
    //进度
        [self.cellT.sliderPlayProgress addTarget:self action:@selector(slideAction:) forControlEvents:UIControlEventValueChanged];
        //播放模式
        [self.cellT.buttonMode addTarget:self action:@selector(buttonModeAction:) forControlEvents:UIControlEventTouchUpInside];
        //上一曲
        [self.cellT.buttonBack addTarget:self action:@selector(buttonBackAction:) forControlEvents:UIControlEventTouchUpInside];
        //暂停
        [self.cellT.buttonStop addTarget:self action:@selector(buttonStopAction:) forControlEvents:UIControlEventTouchUpInside];
        //下一曲
        [self.cellT.buttonNext addTarget:self action:@selector(buttonNextAction:) forControlEvents:UIControlEventTouchUpInside];
        //分享
        [self.cellT.buttonShare addTarget:self action:@selector(buttonShareAction:) forControlEvents:UIControlEventTouchUpInside];
        
        self.cellT.backgroundColor = [UIColor clearColor];
        self.cellT.selectionStyle = UITableViewCellSelectionStyleNone;
        return self.cellT;
    }
    
}
//播放时长
-(void)timeAction{
    //总时长
    self.cellT.sliderPlayProgress.maximumValue = self.player.duration ;
    //当前
    self.cellT.sliderPlayProgress.value = self.player.progress ;
    //分
    NSInteger proMin = (NSInteger)self.player.progress / 61;
    //秒
    NSInteger proSec = (NSInteger)self.player.progress % 61;
    NSInteger durMin = (NSInteger)(self.player.duration )/ 64;
    NSInteger durSec = (NSInteger)(self.player.duration )% 64;
    self.cellT.labelBeginTime.text = [NSString stringWithFormat:@"%02ld:%02ld ",proMin, proSec];
    self.cellT.labelEndTime.text = [NSString stringWithFormat:@"%02ld:%02ld", durMin, durSec];
}
- (void)volumeAction:(UISlider *)sender{
    //    把player的进度值给声音进度条
    self.player.volume = sender.value;
}
#pragma mark 进度条
-(void)slideAction:(UISlider *)slider{
    if (self.player) {
        //把player的进度值给播放进度条
        [self.player seekToTime:slider.value];
    }
}
#pragma mark 播放模式
- (void)buttonModeAction:(UIButton *)sender{
    if (self.playMode == OrderMode) {
        [self.cellT.buttonMode setBackgroundImage:[UIImage imageNamed:@"iconfont-yuledanquxunhuan.png"] forState:UIControlStateNormal];
        self.playMode = OneSongMode;
    }else if (self.playMode == OneSongMode) {
        [self.cellT.buttonMode setBackgroundImage:[UIImage imageNamed:@"suiji32.png"] forState:UIControlStateNormal];
        self.playMode = RandomMode;
    }else{
        [self.cellT.buttonMode setBackgroundImage:[UIImage imageNamed:@"xunhuan32.png"] forState:UIControlStateNormal];
        self.playMode = OrderMode;
    }
}
#pragma mark 上一曲
- (void)buttonBackAction:(UIButton *)sender{
    if (self.player.state == STKAudioPlayerStatePaused) {
        if (self.playMode == OrderMode){
        self.indexRow--;
        //    判断当前是否是第一曲,如果是第一曲,点击后一直播放播放第一曲
        if (self.indexRow <= 0) {
            self.indexRow = 0;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            self.player.state = STKAudioPlayerStatePaused;
            //播放
            [self givePicToplayButtonWhenPlay];

            [self loadPlayData];
            [self.tableViewOne reloadData];
        }else{
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self.player pause];
            self.player.state = STKAudioPlayerStatePlaying;
            [self givePicToplayButtonWhenPlay];

           [self loadPlayData];
        }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];

            [self loadPlayData];
        }
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
    }
    //如果当前是播放状态
    else{
        if (self.playMode == OrderMode){
            self.indexRow--;
            //   判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
            if (self.indexRow <= 0) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            if (self.indexRow <= 0) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == OneSongMode) {
            if (self.indexRow <= 0) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
    }
}
//下一曲
- (void)buttonNextAction:(UIButton *)sender{

       if (self.player.state == STKAudioPlayerStatePaused) {
        if (self.playMode == OrderMode){
        self.indexRow++;
            //    判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
        if (self.indexRow == self.allMusicArray.count) {
            self.indexRow = 0;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            self.player.state = STKAudioPlayerStatePlaying;
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }else{
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self.player pause];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
            }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self givePicToplayButtonWhenPlay];
            [self loadPlayData];
        }
    }
    //当是播放状态时
    else{
        if (self.playMode == OrderMode){
        self.indexRow++;
        //   判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
        if (self.indexRow == self.allMusicArray.count) {
            self.indexRow = 0;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self loadPlayData];
        }else{
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            //点击下一曲重新给歌曲名和图片复制
            [self secondGiveData];
            NSLog(@"!!!!!!!!!!!!%ld", self.indexRow);
            [self loadPlayData];
        }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            NSLog(@"!!!!!!!!!!!!%ld", self.indexRow);
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == OneSongMode) {
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                NSLog(@"!!!!!!!!!!!!%ld", self.indexRow);
                [self loadPlayData];
            }
        }
    }
    [self search];
    for (CXMusicModel *temopModel in self.tempArray) {
        if ([temopModel.source isEqualToString:self.playUrl]) {
            [self.cellF.saveButton setSelected:YES];
        }
    }

    [self.tableViewOne reloadData];
}

#warning 摇一摇 lulu
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self becomeFirstResponder];
}


#pragma mark - 实现相应的响应者方法
/** 开始摇一摇 */
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionBegan");
    [self nextSong];
}

/** 摇一摇结束（需要在这里处理结束后的代码） */
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    // 不是摇一摇运动事件
    if (motion != UIEventSubtypeMotionShake) return;
    NSLog(@"motionEnded");
}

/** 摇一摇取消（被中断，比如突然来电） */
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionCancelled");
}

#pragma mark 给播放按钮图片
-(void)givePicToplayButtonWhenPlay{
    [self.cellT.buttonStop setBackgroundImage:[UIImage imageNamed:@"zanting128.png"] forState:UIControlStateNormal];
}
#pragma mark 给暂停按钮图片
-(void)givePicToplayButtonWhenPause{
    [self.cellT.buttonStop setBackgroundImage:[UIImage imageNamed:@"kaishi32.png"] forState:UIControlStateNormal];
}

#pragma mark 重写播放网址的set方法
-(void)setPlayUrl:(NSString *)playUrl{
    if (_playUrl == playUrl) {
        return;
    }else{
        _playUrl = playUrl;
        [self secondGiveData];
        [self loadPlayData];

    }
}
//暂停
- (void)buttonStopAction:(UIButton *)sender{
    //暂停
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self givePicToplayButtonWhenPlay];
        //继续播放
        [self.player resume];
        self.cellF.labelPlayState.text = @"正在播放";
        [self JiXuBoFang];
        NSDictionary *dicK = @{@"state":@"正在播放"};
        [[NSNotificationCenter defaultCenter] postNotificationName:YINYUE_STATE_K object:self userInfo:dicK];
        //当前是播放状态
    }else if (self.player.state == STKAudioPlayerStatePlaying){
        [self givePicToplayButtonWhenPause];
        [self.player pause];
        self.cellF.labelPlayState.text = @"播放暂停";
        [self BoFangZanTing];
        NSDictionary *dicT = @{@"state":@"播放暂停"};
        [[NSNotificationCenter defaultCenter] postNotificationName:YINYUE_STATE_T object:self userInfo:dicT];
        //其他
    }else{
        [self givePicToplayButtonWhenPause];
        [self loadPlayData];
    }
}
#pragma mark 
-(void)nextSong{
    if (self.player.state == STKAudioPlayerStatePaused) {
        if (self.playMode == OrderMode){
            self.indexRow++;
            [self givePicToplayButtonWhenPlay];
            
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                self.player.state = STKAudioPlayerStatePlaying;
                //    判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self.player pause];
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self loadPlayData];
        }
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self loadPlayData];
        }
    }
    //当是播放状态时
    else{
        if (self.playMode == OrderMode){
            self.indexRow++;
            //   判断当前是否是最后一曲,如果是最后一曲,点击后重新播放第一曲
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
                
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
        if (self.playMode == OneSongMode) {
            if (self.indexRow == self.allMusicArray.count) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                //点击下一曲重新给歌曲名和图片复制
                [self loadPlayData];
            }
        }
    }
}
#pragma mark 点上一曲或下一曲重新给歌曲名和图片复制
-(void)secondGiveData{
    self.cellF.labelPlayerName.text = [self.JieShouModel.channel objectForKey:@"name"];
    self.cellF.labelPlayTitle.text = [[self.allMusicArray objectAtIndex:self.indexRow] name];
    [self.cellF.imageViewTouXiang sd_setImageWithURL:[NSURL URLWithString:[[self.allMusicArray objectAtIndex:self.indexRow] pic]] placeholderImage:[UIImage imageNamed:@"wait.png"]];
    [self.backGroundImageView sd_setImageWithURL:[NSURL URLWithString:[[self.allMusicArray objectAtIndex:self.indexRow] pic]] placeholderImage:nil];
}
//音量
- (void)buttonShareAction:(UIButton *)sender{
    sender.selected = !sender.isSelected;
    if (sender.isSelected) {
        [UIView animateWithDuration:0.2 animations:^{
            self.viewDown.frame = CGRectMake(0, ScreenHeight + 35.f, ScreenWidth, 35.f);
            self.viewDown.frame = CGRectMake(0, ScreenHeight - 35.f, ScreenWidth, 35.f);
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.viewDown.frame = CGRectMake(0, ScreenHeight - 35.f, ScreenWidth, 35.f);
            self.viewDown.frame = CGRectMake(0, ScreenHeight + 35.f, ScreenWidth, 35.f);
        }];
    }
}
//旋转动ƒ画跳转
- (void)DongHuaDelegate:(NSArray *)array and:(FZ_RootModelR *)model{
    FZ_BoFang_One_ViewController *FirstViewController = [[FZ_BoFang_One_ViewController alloc] init];
    FirstViewController.Imodel = model;
    [self.navigationController pushViewController:FirstViewController animated:YES];
    [FirstViewController release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 0) {
        return 211.f;
    }
    if (indexPath.row == 1) {
        return 200.f;
    }
    else {
        return 256.f;
    }
}
- (void)ImageViewBack{
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark 代理点击事件
- (void)BoFangXingQing:(NSArray *)array{
    CXSelectSaveViewController *saveController = [[CXSelectSaveViewController alloc] init];
    [self.navigationController pushViewController:saveController animated:YES];
    [saveController release];
}
- (void)FZBoFangXingQing:(NSArray *)array andModel:(FZ_RootModelR *)model{
    FZ_BoFang_TwoCell_XiangQing_ViewController *xiangQingViewController = [[FZ_BoFang_TwoCell_XiangQing_ViewController alloc] init];
    xiangQingViewController.jieShouArray  = array;
    [self.navigationController pushViewController:xiangQingViewController animated:YES];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    [xiangQingViewController release];
}
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    self.TouXiangStateF = TouXiangStateFF;
    [self secondGiveData];
    [self search];
    [self.tableViewOne reloadData];
//判断当前播放是否是将要传进来得歌曲，如果是，直接返回，不是就把button状态改了
    if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self givePicToplayButtonWhenPause];
        }
        if(self.player.state == STKAudioPlayerStatePlaying)
        {
            [self givePicToplayButtonWhenPlay];
        }
        else{
            if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
            [self givePicToplayButtonWhenPause];
            }else{
                [self givePicToplayButtonWhenPause];
            }
        }
        return;
    }
#pragma mark 旋转
    //判断
    if (self.TouXiangStateF) {
    }else{
        [self.CreatViewS removeAnimat];
    }
    self.TouXiangStateF = TouXiangStateFF;
    if (self.TouXiangStateF) {
        self.cellF.labelPlayState.text = @"正在播放";
        CABasicAnimation *basicanimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        [basicanimation setDuration:3];
        [basicanimation setRepeatCount:NSIntegerMax];
        basicanimation.fromValue = [NSNumber numberWithInt:0];
        basicanimation.toValue = [NSNumber numberWithFloat:M_PI * 2];
        [self.cellF.imageViewTouXiang.layer addAnimation:basicanimation forKey:@"transform"];
        basicanimation.autoreverses = YES;
    }else{
        [self.CreatViewS removeAnimat];
    }
    //拔掉耳机播放
        [super viewWillAppear:animated];
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated{
    if (self.playUrl == [[self.allMusicArray objectAtIndex:self.indexRow] source]){
        if (self.player.state == STKAudioPlayerStatePaused) {
            [self givePicToplayButtonWhenPause];
        }
        if(self.player.state == STKAudioPlayerStatePlaying)
        {
            [self givePicToplayButtonWhenPlay];
        }
        else{
//            [self givePicToplayButtonWhenPlay];
        }
        
        return;
    }
    //拔掉耳机
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
#warning lulu
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}

//拔掉耳机
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlPause:
                [self buttonStopAction:self.cellT.buttonStop];
                break;
            case UIEventSubtypeRemoteControlPlay:
                [self buttonBackAction:self.cellT.buttonStop];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self buttonBackAction:self.cellT.buttonBack];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [self buttonNextAction:self.cellT.buttonNext];
                break;
                
            default:
                break;  
        }  
    }  
}
#pragma mark SKT代理方法 歌曲完成加载,可以控制音量什么的
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"完成加载");
    audioPlayer.state = STKAudioPlayerStateStopped;
    if (audioPlayer.state == STKAudioPlayerStateStopped) {
        if (!self.player) {
            return;
        }
        //顺序播放
        if (self.playMode == OrderMode) {
            if (self.indexRow == self.allMusicArray.count - 1) {
                self.indexRow = 0;
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }else{
                self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
                [self loadPlayData];
            }
        }
        //随机播放
        if (self.playMode == RandomMode) {
            self.indexRow = arc4random() % self.allMusicArray.count;
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self loadPlayData];
        }
        //单曲循环
        if (self.playMode == OneSongMode) {
            self.playUrl = [[self.allMusicArray objectAtIndex:self.indexRow] source];
            [self loadPlayData];
        }
    }

}

// 查看播放的开始歌曲是否存在,如果不存在运行切换歌曲的代码
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId
{
    NSLog(@"开始播放");
    self.cellF.labelPlayState.text = @"开始播放";
    NSDictionary *dicK = @{@"state":@"正在播放"};
    [[NSNotificationCenter defaultCenter] postNotificationName:YINYUE_STATE_K object:self userInfo:dicK];
}

// 播放状态改变, 暂停或者是播放, 这里可以写之前的播放的状态是单曲还是顺序
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousStat
{
    NSLog(@"播放状态改变");
    [self search];
}

// 当歌曲结束的时候走这个方法
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"结束播放");
    NSLog(@"结束原因:%d, progress: %f, duration: %f", stopReason, progress, duration);
}

// 不怎么用到
-(void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因:%d", errorCode);
}
#pragma mark 收藏功能
-(void)saveButtonAction:(UIButton *)button{
    int count = 0;
//    CXMusicModel *list = self.allMusicArray[self.indexRow];
    if (self.tempArray.count == 0) {
        CXMusicModel *list = [NSEntityDescription insertNewObjectForEntityForName:@"CXMusicModel" inManagedObjectContext:self.manager.managedObjectContext];
        list.name = [[self.allMusicArray objectAtIndex:self.indexRow] name];
        list.pic =[[self.allMusicArray objectAtIndex:self.indexRow] pic];
        list.source = self.playUrl;
        [self.manager saveContext];
    }
    else{
        for (CXMusicModel *modelll in self.tempArray) {
            if (![modelll.source isEqualToString:self.playUrl]) {
                count++;
            }
        }
        if (count == self.tempArray.count) {
            CXMusicModel *list = [NSEntityDescription insertNewObjectForEntityForName:@"CXMusicModel" inManagedObjectContext:self.manager.managedObjectContext];
            list.name = [[self.allMusicArray objectAtIndex:self.indexRow] name];
            list.pic = [[self.allMusicArray objectAtIndex:self.indexRow] pic];
            list.source = self.playUrl;
            [self.manager saveContext];
        }
    }
    if (!button.selected) {
        button.selected = YES;
    }
    else{
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"CXMusicModel" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {

        }else{
            for (CXMusicModel *list in fetchedObjects) {
                if ([list.source isEqualToString:self.playUrl]) {
                    [self.manager.managedObjectContext deleteObject:list];
                }
            }
        }
        [self.manager saveContext];
        button.selected = NO;
    }
}
#pragma mark 查
-(void)search{
    if (self.tempArray!= nil) {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CXMusicModel" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"source"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    self.tempArray = fetchedObjects;
    if (fetchedObjects == nil) {
    }else{
    }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.cellT.buttonShare.isSelected) {
        self.cellT.buttonShare.selected = NO;
    }
        [UIView animateWithDuration:0.2 animations:^{
            self.viewDown.frame = CGRectMake(0, ScreenHeight - 35.f, ScreenWidth, 35.f);
            self.viewDown.frame = CGRectMake(0, ScreenHeight + 35.f, ScreenWidth, 35.f);
        }];
}
- (void)BoFangZanTing{
    [self.cellF.imageViewTouXiang.layer removeAllAnimations];
}

#pragma mark 分享的代理事件
- (void)FZFenXiangXingQing:(NSArray *)array andModel:(CXMusicModel *)model andString:(NSString *)String{
    [self.view addSubview:self.shareView];
//    [UIView animateWithDuration:1 animations:^{
//        
//        self.shareView.frame = CGRectMake(100, 100, 100, 200);
//    }];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5624fd7367e58ed46e007285"
                                      shareText:[NSString stringWithFormat:@"%@ 你要分享的歌曲:", self.playUrl]
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQQ,nil]
                                       delegate:nil];


}
- (void)JiXuBoFang{
    CABasicAnimation *Animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    [Animation setDuration:3];
    [Animation setCumulative:YES];
    [Animation setRepeatCount:FLT_MAX];
    Animation.fromValue = [NSNumber numberWithInt:0];
    Animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    [self.cellF.imageViewTouXiang.layer addAnimation:Animation forKey:@"transform"];
    Animation.autoreverses = YES;
}
@end
